package io.github.frailty9.crserver.dso.service.impl;

import com.mybatisflex.kotlin.extensions.db.baseMapper
import com.mybatisflex.kotlin.extensions.db.queryOne
import com.mybatisflex.kotlin.extensions.kproperty.eq
import io.github.frailty9.crserver.model.User;
import io.github.frailty9.crserver.dso.service.UserService;
import io.github.frailty9.crserver.dto.UserInfoDto
import io.github.frailty9.crserver.model.Account
import org.noear.solon.annotation.Component;
import org.noear.solon.data.annotation.Transaction

/**
 * UserServiceImpl
 */
@Component
open class UserServiceImpl : UserService {

    @Transaction(readOnly = true)
    override fun getInfo(id: Long): UserInfoDto {
        val account = queryOne<Account> {
            select(Account::username, Account::role)
            where(Account::id eq id)
        }!!
        val user = queryOne<User> { User::id eq id}!!
        val userInfo = UserInfoDto(
            username = account.username!!,
            role = account.role!!,
            userInfo = user
        )
        return userInfo
    }

    @Transaction
    override fun update(user: User) {
        val version = queryOne<User> {
            select(User::version)
            where(User::id eq user.id)
        }?.version
        user.version = version

        User::class.baseMapper.update(user, true)
    }
}
